package com.sh.data.engine.domain.annotation;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sh.data.engine.common.constants.Constants;
import com.sh.data.engine.common.enumDefinition.RoleEnum;
import com.sh.data.engine.domain.authority.service.TokenService;
import com.sh.data.engine.domain.base.model.UserContext;
import com.sh.data.engine.repository.dao.authority.UserProjectMapper;
import com.sh.data.engine.repository.dao.authority.UserTokenMapper;
import com.sh.data.engine.repository.dao.authority.entity.UserProjectEntity;
import com.sh.data.engine.repository.dao.authority.entity.UserTokenEntity;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Aspect
@Component
public class DefaultProjectAspect {

    @Autowired
    private UserProjectMapper userProjectMapper;

    @Autowired
    private TokenService tokenService;

    @Autowired
    private UserTokenMapper userTokenMapper;

    @Pointcut("@annotation(com.sh.data.engine.domain.annotation.DefaultProjectExecution)")
    public void myDefaultProjectExecution() {
    }

    @Around("myDefaultProjectExecution()")
    public Object logAround(ProceedingJoinPoint joinPoint) throws Throwable {
        String userId = UserContext.getUserId();
        LambdaQueryWrapper<UserProjectEntity> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(UserProjectEntity::getUserId, userId).eq(UserProjectEntity::getProjectId, Constants.DEFAULT_PROJECT_ID).eq(UserProjectEntity::getRoleId, RoleEnum.GUEST.getStatus());
        if (userProjectMapper.selectList(wrapper).isEmpty()) {
            UserProjectEntity userProjectEntity = UserProjectEntity.builder().build();
            userProjectEntity.setProjectId(Constants.DEFAULT_PROJECT_ID);
            userProjectEntity.setUserId(userId);
            userProjectEntity.setRoleId(RoleEnum.GUEST.getStatus());//默认空间给访客权限6L
            userProjectMapper.insert(userProjectEntity);
        }

        //判断是否具有user token
        LambdaQueryWrapper<UserTokenEntity> wrapperToken = new LambdaQueryWrapper<>();
        wrapperToken.eq(UserTokenEntity::getUserId, userId);
        if (userTokenMapper.selectList(wrapperToken).isEmpty()) {
            tokenService.initToken(userId);
        }

        Object result;
        try {
            result = joinPoint.proceed(); // 继续执行方法
        } catch (Exception e) {
            throw e;
        }
        return result;
    }
}